<template>
  <div>
    <van-popup :show="props.showPopup" position="bottom" :style="{ height: '35%' }" closeable
      :close-on-click-overlay="false" @click-close-icon="closePopup">
      <div class="mt100 textCenter">
        <van-uploader v-model="fileList" accept="image/*" :before-read="beforeUpload" :after-read="afterRead"
          :delete="handleDelete" />
      </div>
      <div class="mt30 ml30 mr30">
        <van-button type="primary" block @click="submit">保存</van-button>
      </div>
    </van-popup>
  </div>
</template>

<script lang="ts" setup>
import { ref, defineEmits } from 'vue'
import { showToast } from 'vant'
import { commonUpload } from '@/api/common'
import { handleImgSrc } from '@/utils'
import { avatarModify } from '@/api/user'
const props = defineProps({
  showPopup: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits<{ (e: 'update:showPopup', value: boolean, flag?: boolean): void }>()

const fileList = ref<{ url: string, file: File }[]>([])
const curFile = ref('')

const closePopup = () => {
  emit('update:showPopup', false, false)
}

const submit = async () => {
  if (!curFile.value) {
    return showToast('请上传图片')
  }

  const { data } = await avatarModify({ avatar: curFile.value })
  if (data.code === 0) {
    showToast('已修改')
    emit('update:showPopup', false, true)
    fileList.value = []
    curFile.value = ''
  } else {
    showToast(data.msg)
  }
}

const beforeUpload = async (file: File | File[]): Promise<File | File[]> => {
  const currentFile = Array.isArray(file) ? file[0] : file

  // 校验大小
  if (currentFile.size > 2 * 1024 * 1024) {
    showToast('文件大小不能超过 2MB')
    throw new Error('文件过大')
  }

  // 校验格式
  const validTypes = ['image/jpg', 'image/jpeg', 'image/png', 'image/gif']
  if (!validTypes.includes(currentFile.type)) {
    showToast('仅支持 JPG/JPEG/PNG/GIF 格式')
    throw new Error('格式错误')
  }
  return Array.isArray(file) ? file : currentFile
}

const afterRead = async (file: { file: File }) => {
  const formData = new FormData()
  formData.append('file', file.file)

  const { data } = await commonUpload(formData)
  if (data.code === 0) {
    showToast('上传成功')
    const imgUrl = handleImgSrc(data.data.data)
    fileList.value = [{ url: imgUrl, file: file.file }]
    curFile.value = data.data.data
  } else {
    showToast(data.msg || '上传失败')
    fileList.value = []
  }
}

const handleDelete = (index: number) => {
  fileList.value.splice(index, 1)
  curFile.value = ''
}

</script>

<style lang="scss" scoped>
.imgBox {
  position: relative;

  .upload {
    position: absolute;
    top: 60%;
    left: 58%;
  }

  img {
    max-width: 180px;
    border-radius: 50%;
  }
}

.van-popup {
  background: #FFFFFF;
}

.van-cell__title {
  width: 0 !important;
}

.van-button--primary {
  background: #40a9ff;
  border-color: #40a9ff;
}
</style>